package com.company;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.Socket;
import javax.sound.sampled.*;

public class starGame extends JFrame {
    private JTextField usernameField;
    private JTextField ipField;
    private JTextField portField;
    private JButton connectButton;
    private JTextArea historyArea;
    private String userNamer;
    String centralServerAddress = "127.0.0.1";
    int centralServerPort = 12345;
    private int CLOWS;
    private int ROWS;



    public starGame() {
         Clip clip = playBackgroundMusic("src/com/company/backgroundMusic.wav");

        setTitle("联机大厅-拯救蔡徐村");
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 创建层叠窗格
        JLayeredPane layeredPane = new JLayeredPane();

        layeredPane.setPreferredSize(new Dimension(600, 600));

        setContentPane(layeredPane);

        // 创建背景面板
        JPanel backgroundPanel = new JPanel() {
            Image bgImage = new ImageIcon("src/com/company/oline.jpg").getImage();

            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(bgImage, 0, 0, getWidth(), getHeight(), this);
            }
        };
        backgroundPanel.setBounds(0, 0, 600, 600);
        layeredPane.add(backgroundPanel, Integer.valueOf(1)); // 将背景面板放在底层

        // 创建其他组件的面板
        JPanel mainPanel = new JPanel();
        mainPanel.setBounds(0, 0, 600, 600);
        mainPanel.setOpaque(false); // 设置为透明以显示背景图


        // 创建输入面板
        JPanel inputPanel = new JPanel(new GridLayout(5, 5));
        JTextField usernameField = new JTextField();
        JTextField ipField = new JTextField();
        JTextField portField = new JTextField();
        JTextField rowsF = new JTextField();
        JTextField closF = new JTextField();
        inputPanel.add(new JLabel("用户名:"));
        inputPanel.add(usernameField);
        inputPanel.add(new JLabel("IP地址:"));
        inputPanel.add(ipField);
        inputPanel.add(new JLabel("端口:"));
        inputPanel.add(portField);
        inputPanel.add(new JLabel("棋盘行数:"));
        inputPanel.add(rowsF);
        inputPanel.add(new JLabel("棋盘列数:"));
        inputPanel.add(closF);
        mainPanel.add(inputPanel);





        // 创建房间按钮
        JButton createServerButton = new JButton("创建房间");
        createServerButton.addActionListener(e -> {

            new Thread(() -> {
                try {

                    // 确定中央服务器的IP和端口
                    String centralServerIP = "127.0.0.1";
                    int centralServerPort = 12345;

                    userNamer = usernameField.getText();
                    // 向中央服务器发送注册消息
                    try (Socket socket = new Socket(centralServerIP, centralServerPort);
                         PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
                        // 发送注册请求，包括本地服务器的IP和端口号
                        System.out.println("已经运行");
                        out.println("REGISTER"+ipField.getText()+":"+portField.getText()+":"+rowsF.getText()+":"+closF.getText());
                    }
                    // 启动游戏服务器
                    GobangServer gobangServer = new GobangServer();
                    gobangServer.star(portField.getText(),Integer.parseInt(rowsF.getText()),Integer.parseInt(closF.getText()));


                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }).start();

            // 更新UI
            createServerButton.setEnabled(false);
        });
        mainPanel.add(createServerButton);

        // 获取服务器列表的按钮
        JButton getServerListButton = new JButton("获取服务器列表");
        getServerListButton.addActionListener(e -> {
            new Thread(() -> {
                try (Socket socket = new Socket(centralServerAddress, centralServerPort);
                     BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                     PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) {

                    // 向中央服务器发送请求，获取服务器列表
                    writer.println("GET_SERVER_LIST");
                    String response;
                    while ((response = reader.readLine()) != null) {
                        // 假设每行响应都是一个服务器的IP地址

                        String[] split = response.split(":");
                        String serverIP = split[0];
                        String serverPort = split[1];
                        CLOWS= Integer.parseInt(split[3]);
                        ROWS = Integer.parseInt(split[2]);

                        // 校验用户输入
                        if (CLOWS>=6 && ROWS >=6) {

                        }else{
                            JOptionPane.showMessageDialog(starGame.this,"非法棋盘枪毙，以标准棋盘开始");
                            CLOWS=15;
                            ROWS=15;
                        }
                        SwingUtilities.invokeLater(() -> {

                            // 在界面上为每个服务器创建一个按钮
                            JButton serverButton = new JButton(" 房间 IP"+serverIP+" 端口 PORT"+serverPort+" 棋盘行数 ROWS"+ROWS+" 棋盘列数 CLOWS"+CLOWS);
                            serverButton.addActionListener(ev -> {
                                // 玩家点击按钮后，使用该IP进入游戏
                                userNamer= usernameField.getText();

                                enterGame(serverIP,serverPort,ROWS,CLOWS,clip);
                            });
                            mainPanel.add(serverButton);
                            mainPanel.revalidate();
                        });
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }).start();
        });
        mainPanel.add(getServerListButton);



        layeredPane.add(mainPanel, Integer.valueOf(2)); // 将 mainPanel 放在更高的层上

        setLocationRelativeTo(null); // 窗口居中

    }

    public Clip playBackgroundMusic(String musicPath) {
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(musicPath));
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.loop(Clip.LOOP_CONTINUOUSLY); // 设置音乐循环播放
            clip.start();
            return clip;
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            e.printStackTrace();
        }

        return null;
    }

    public void playMusic(String musicPath) {
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(musicPath));
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    // 主方法
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new starGame().setVisible(true);
        });
    }

    public void deregisterServer(String centralServerIP, int centralServerPort, String localServerIP, int localServerPort,String row,String clo) {
        try (Socket socket = new Socket(centralServerIP, centralServerPort);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
            // Send a deregistration request with the local server's IP and port
            out.println("UNREGISTER" + localServerIP + ":" + localServerPort+":"+row+":"+clo);
        } catch (IOException ex) {
            ex.printStackTrace();
            // Handle exception: maybe log the error or notify the user
        }
    }

    // 进入游戏的方法
    public void enterGame(String serverIP,String serverPort,int rows,int clos,Clip clip) {
        // 实现玩家使用服务器IP地址进入游戏的逻辑
         clip.close();
         this.setVisible(false); // 隐藏或关闭当前窗口
         this.dispose();
         deregisterServer(centralServerAddress,centralServerPort,serverIP,Integer.parseInt(serverPort),String.valueOf(rows),String.valueOf(clos));

        SwingUtilities.invokeLater(() -> {
            playMusic("src/com/company/starMusic.wav");

            GobangGame game = new GobangGame(serverIP,userNamer,rows,clos,serverPort);
            game.setVisible(true);
        });


        clip.close();
        this.setVisible(false); // 隐藏或关闭当前窗口
        this.dispose();
    }
}